package com.kandinfo.survey.common.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kandinfo.base.common.constant.ResultCode;
import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.service.AbstractService;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.survey.common.constants.StatusConstant;
import com.kandinfo.survey.common.domain.PatientInfo;
import com.kandinfo.survey.common.dto.PatientInfoDto;
import com.kandinfo.survey.common.repository.PatientInfoRepository;
import com.kandinfo.survey.common.service.PatientInfoService;

@Service
public class PatientInfoServiceImpl extends AbstractService<PatientInfo, Long, PatientInfoRepository>
        implements PatientInfoService {

    private static final Logger logger = LoggerFactory.getLogger(PatientInfoServiceImpl.class);

    @Resource
    public void setPatientInfoRepository(PatientInfoRepository patientInfoRepository) {
        super.setRepository(patientInfoRepository);
    }

    @Override
    @Transactional
    public ResultDto saveByDto(PatientInfoDto patientInfoDto) {
        PatientInfo domain = new PatientInfo();
        try {
            BeanUtils.copyProperties(domain, patientInfoDto);
        } catch (Exception e) {
            logger.error("newPatientInfo copyProperties error - PatientInfoServiceImpl - saveByDto ", e.toString());
            return ResultDtoFactory.createResult(ResultCode.ERROR, " 新建失败! ");
        }
        
        User patient = SecurityContext.getInstance().getCurrentUser();
        domain.setCreateBy(patient.getId());
        domain.setCreateTs(new Date());
        domain.setPatientId(patient.getId());
        domain.setStatus(StatusConstant.NORMALLY_USE);
        repository.save(domain);

        return ResultDtoFactory.createResult(ResultCode.SUCCESS, " 新建成功! ");
    }

    @Override
    public PatientInfoDto findByPatientId(Long patientId) {
        PatientInfo domain = repository.findByPatientId(patientId);
        if (domain == null) {
            return null;
        }
        
        PatientInfoDto resDto = new PatientInfoDto();
        try {
            BeanUtils.copyProperties(domain, resDto);
        } catch (Exception e) {
            logger.error(" PatientInfo -> PatientInfoDto, patientId : {" + patientId + "}", e.toString());
        }
        return resDto;
    }

}
